<!--
@单点登录成功回调组件
-->
<template>
  <div></div>
</template>

<script>
import { parse } from 'qs'
import { setToken } from 'chaos-sso-util'
import { codeCallback } from '@/api/login'
import store from '@/store'

export default {
  name: 'CodeCallbackContainer',
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect_uri
      },
      immediate: true,
    },
  },
  methods: {
    getUserInfo() {
      // 判断当前用户是否已拉取完user_info信息
      store.dispatch('GetInfo').then(() => {
        let path = this.redirect || '/'
        if (process.env.VUE_APP_PORTAL_HOST_URL == path) {
          path = '/'
        }
        this.$router.push({ path: path })
      })
    },
    handleCallback({ redirectUri, code }) {
      codeCallback(redirectUri, code).then((res) => {
        // 成功换取到token,将token保存到cookie
        setToken(res.data)
        store.dispatch('Login', res.data)
        //获取用户信息
        this.getUserInfo()
        // 获取花名册权限字段
        store.dispatch('getField')
      })
    },
  },
  mounted() {
    const { redirect_uri, code } = parse(window.location.href.split('?')[1])
    this.handleCallback({ redirectUri: redirect_uri, code })
  },
}
</script>